const {
  exec
} = require('child_process');
const puppeteer = require('puppeteer');
let fs = require('fs')
let schedule = require('node-schedule')
let axios = require('axios')
let request = require('request')
let cheerio = require('cheerio')

class Z {
  constructor() {
    axios.defaults.withCredentials = true
    this.url = `https://xueqiu.com/P/ZH010389`;
    this.noticeCount = 0
    this.xqMonitorIndex = 0
    this.jdMonitorIndex = 0
    this.JDCookies=`__jdv=204210054|baidu|-|organic|%25E4%25BA%25AC%25E4%25B8%259C%25E8%2582%25A1%25E7%25A5%25A8|1551876638572; __jdu=1646321841; sec_flag=332dee17a27461467a558f3284e846ef; sec_addr=0a0a3dd1; pinId=A9DwPkCiMmPbXrUjzBWQTQ; pin=wlasd4622; unick=wlasd4622; _tp=53vqb1R8H1KyeoFRYcoSnA%3D%3D; _pst=wlasd4622; shshshfpa=6977d23b-c4af-857a-f906-2e7fa33471ce-1551927056; shshshfpb=wwcu%2FAsYtFwtDKFs%2FPixBNg%3D%3D; user-key=42b2eb2e-dd33-4b0f-9e59-670c22760171; cn=0; areaId=1; ipLoc-djd=1-72-0; shshshfp=05ed8724c257fb1b39e8af4781c90cb2; 3AB9D23F7A4B3C9B=5IKBHHHS7HRFHF2OI55B4O24DASOKMBMZY5SW3IDCCGM2QUKMTPFXTT5QBGDUUQQGAQEA3UQHF2S2OJZXKPGP56JTU; _jrda=2; wlfstk_smdl=773le1gzkzyhrqqnhj5gc5b60sr01ft9; TrackID=15zbCCxF-2dVAzoOHXnpLz20DKsggN5os-L9uPFErgiDo7fNEoFRh0IGH-D0uJlostRhI23Whpv-YYHLdJ_DBaxjK2wpdlDywVMG-3mb2iT-Rp94e_vVE39dhWN3H67ky; thor=7B684F6583DE0AF108846C6D3E3F8C52372796265080AD45433B1DCA94344791DC1BAEA9C43674B4A501D89964165DB5860ECE8C7E1079DA18C83CF8AA0AF529EF107D1EF671CDC687216BAA5E0749E9ED4F2D3349B7445D165DD9A9828B4522FE8FED5ECF886EBE98D139F60F8D61F780E1C903C69A536684F7EAAA9726E50DBAFFC6EEF136D02B7AF4F646CE0E376A; ceshi3.com=103; __jda=204210054.1646321841.1543285114.1552616328.1552875647.5; __jdc=204210054; __jdb=204210054.5.1646321841|5.1552875647; _jrdb=1552875686`
  }

  async getDataXQ() {
    console.log(`>>>XQ第${this.xqMonitorIndex++}次...`)
    this.page.goto(this.url, {
      waitUntil: 'domcontentloaded'
    });
    await this.page.waitForSelector('#cube-action .no-tooltip');

    let data = await this.page.evaluate(() => {
      var data = {
        date: $('#cube-action .block-title .date').text().trim().replace(/[（）]/g, '').trim(),
        source: 'XQ',
        list: []
      }
      $('#cube-action .no-tooltip').each((i, item) => {
        data.list.push({
          name: $(item).find('.name').text(),
          center: $(item).find('.center').text(),
          right: $(item).find('.right').text().replace(/%/, '%→')
        })
      })
      return data
    })
    let content = data.date + '\n';
    data.list.forEach(item => {
      content += `${item.name}-${item.center.replace('成交价：','')}-${item.right.match(/\d+\.\d+%$/)[0]}\n`
    });
    let localInfo = JSON.parse(fs.readFileSync('./dist/info.json').toString() || '{}')
    let key = `XQ-${data.date}`
    if (!localInfo[key]) {
      console.log(content)
      this.notice(content, 'XQ')
      localInfo[key] = data
      fs.writeFileSync('./dist/info.json', JSON.stringify(localInfo))
      // await this.sendSMS(content)
    }
    setTimeout(async _ => {
      await this.getDataXQ()
    }, 1000 * 60)
  }
  async runPuppeteer() {
    //https://github.com/GoogleChrome/puppeteer/blob/v1.11.0/docs/api.md#pagetypetext-options
    this.browser = await (puppeteer.launch({
      headless: true
    }));
    this.page = await this.browser.newPage();
    await this.page.setViewport({
      width: 1555,
      height: 667
    })
  }

  schedule() {
    //秒、分、时、日、月、周几
    schedule.scheduleJob('30 * * * * *', function () {
      console.log('scheduleCronstyle:' + new Date());
    });
  }

  sleep(time = 300) {
    return new Promise(async (resolve, reject) => {
      setTimeout(_ => {
        resolve()
      }, time)
    })
  }

  async sendSMS(content = '666') {
    try {
      let url = `http://mail.10086.cn/`
      this.page.goto(url, {
        waitUntil: 'domcontentloaded'
      });
      await this.page.waitForSelector('#J_loginFormHeight');
      await this.page.type('#txtUser', '15011099312')
      await this.page.type('#txtPass', '111qqqww')
      await this.sleep()
      await this.page.click('#loginBtn')
      await this.page.waitForSelector('#welcome');
      await this.sleep(500)
      this.pageSMS = this.page.frames().find(frame => frame.url().indexOf('m2012server/home') > -1)
      await this.pageSMS.waitForSelector('#smsSend');
      await this.pageSMS.click('#smsSend')
      await this.sleep(500)
      await this.page.reload()
      await this.page.waitForSelector('#divTab');
      await this.sleep()
      this.pageSend = this.page.frames().find(frame => frame.url().indexOf('sms/sms_send') > -1)
      // await this.pageSend.click('#txtMobiles')
      await this.sleep()
      await this.pageSend.click('.PlaceHold')
      await this.sleep(500)
      await this.pageSend.type('.addrText-input', '15011099312', {
        delay: 200
      })
      await this.sleep()
      await this.pageSend.click('#txtContent')
      await this.sleep()
      await this.pageSend.type('#txtContent', content, {
        delay: 20
      })
      await this.sleep(500)
      this.pageSend.click('#btnSmsSendFooter a')
    } catch (err) {
      await this.sendSMS(content)
    }

  }

  notice(content, source = 'XQ') {
    this.noticeCount++;
    exec(`osascript -e 'display notification "${content}" with title "${source}-notice-${this.noticeCount}" subtitle ""'`);
    setTimeout(_ => {
      if (this.noticeCount < 40) {
        this.notice(content)
      } else {
        this.noticeCount = 0
      }
    }, 1000)
  }
  async setCookie(page) {
    let localCookies = JSON.parse(fs.readFileSync('./dist/cookies.json').toString() || '{}')
    let host = this.page.url().match(/^[\/\.\w:]+\.com/);
    if (localCookies && localCookies[host] && localCookies[host].length) {
      for (let i = 0; i < localCookies[host].length; i++)
        await page.setCookie(localCookies[host][i]);
    }
  }

  async getDataJD() {
    //最新调仓
    console.log(`>>>JD第${this.jdMonitorIndex++}次...`)
    let result = await axios({
      method: 'post',
      url: 'http://gupiao.jd.com/package/lastConverts',
      params: {
        pin: 'jd_743bd4112ba1e'
      },
      headers: {
        'Content-Type': `application/x-www-form-urlencoded; charset=UTF-8`,
        'Cookie': this.JDCookies,
        'User-Agent': `Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36`
      }
    })
    let tradeTime = result.data.match(/tradeTime = '([\d-\s:]+)/)[1];
    let data = {
      date: tradeTime,
      source: 'JD',
      list: []
    }
    result = await axios({
      method: 'post',
      url: 'http://gupiao.jd.com/package/currentConvert.html',
      params: {
        packageId: 12195
      },
      headers: {
        'Content-Type': `application/x-www-form-urlencoded; charset=UTF-8`,
        'Cookie': this.JDCookies,
        'User-Agent': `Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.121 Safari/537.36`
      }
    })
    let $ = cheerio.load(result.data)
    $('tr').each((i, item) => {
      let stockName = $(item).find('.stock-name').text()
      let stockCode = $(item).find('.stock-code').text()
      let stockPos = $(item).find('.stock-pos').text()
      if (stockName) {
        data.list.push({
          stockName,
          stockCode: stockCode.match(/\w+/)[0],
          stockPos
        })
      }
    })
    //-------------
    let content = data.date + '\n';
    data.list.forEach(item => {
      content += `${item.stockName}-${item.stockCode}-${item.stockPos}\n`
    });
    let localInfo = JSON.parse(fs.readFileSync('./dist/info.json').toString() || '{}')
    let key = `JD-${data.date}`
    if (!localInfo[key]) {
      console.log(content)
      this.notice(content, 'JD')
      localInfo[key] = data
      fs.writeFileSync('./dist/info.json', JSON.stringify(localInfo))
      // await this.sendSMS(content)
    }
    setTimeout(async _ => {
      await this.getDataJD()
    }, 1000 * 60)
  }

  async main() {
    await this.runPuppeteer()
    this.getDataXQ()
    this.getDataJD()
    // await this.sendSMS()
  }
}

new Z().main()


// osascript -e 'display notification "通知内容" with title "标题" subtitle "子标题"'
